/* eslint-disable max-lines */
/* eslint-disable react/jsx-max-depth */
import React, { useReducer, useMemo, useCallback } from 'react';
import { Form, Table, Button, Divider, Popconfirm, Switch, Alert, Modal, message } from 'antd';
import { useAntdTable } from 'ahooks';
import Ellipsis from '@/components/Ellipsis';
import { ACTIONS } from './constants';
import { getTagList, changeTagStatus, removeTag } from './services';
import TopQueryForm from './components/TopQueryForm';
import ModifyDrawer from './components/ModifyDrawer';
import styles from './PositionTagManage.less';
import useMultiPageRowSelection from '@/hooks/useMultiPageRowSelection';

const getTableData = async ({ current, pageSize }, formData) => {
  const { labelName, status, sysOrgId, sysEmployeeId } = formData;

  try {
    const params = {
      pageIndex: current,
      pageSize,
      labelName,
      status,
      sysOrgId,
      sysEmployeeId,
    };
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || undefined || null) {
        delete params[key];
      }
    });

    const res = await getTagList(params);
    const { code, data } = res;
    if (code === 0) {
      return { total: data?.total || 0, list: data?.dataList || [] };
    }
    return { total: data?.total || 0, list: data?.dataList || [] };
  } catch (e) {
    console.error(e);
  }

  return null;
};

const reducer = (state, action) => {
  switch (action.type) {
    case ACTIONS.ADD:
      return {
        ...state,
        mode: ACTIONS.ADD,
        visible: true,
        currentTag: null,
      };
    case ACTIONS.EDIT:
      return {
        ...state,
        mode: ACTIONS.EDIT,
        visible: true,
        currentTag: action.payload,
      };
    case ACTIONS.CLOSE:
      return {
        ...state,
        visible: false,
      };
    case ACTIONS.PREVIEW:
      return {
        ...state,
        mode: ACTIONS.PREVIEW,
        visible: true,
        currentTag: action.payload,
      };
    default:
      return state;
  }
};

const PositionTagManage = () => {
  const [form] = Form.useForm();
  const [state, dispatch] = useReducer(reducer, {});

  const { tableProps, search, params, refresh } = useAntdTable(getTableData, {
    defaultPageSize: 10,
    form,
  });

  const [selectedRowKeys, onSelectChange, resetSelection] = useMultiPageRowSelection(
    tableProps.dataSource,
    'id',
  );

  const handleDrawerClose = useCallback(() => {
    dispatch({ type: ACTIONS.CLOSE });
  }, [dispatch]);

  const { submit, reset } = search;

  const columns = useMemo(
    () => [
      {
        title: '标签编码',
        dataIndex: 'labelCode',
        width: 200,
        fixed: 'left',
        render: text => (
          <Ellipsis length={20} tooltip fullWidthRecognition>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '标签名称',
        dataIndex: 'labelName',
        width: 150,
        fixed: 'left',
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 200,
        fixed: 'left',
        render: (text, record) => {
          const status = text === '1';
          return (
            <Switch
              checked={status}
              checkedChildren="开"
              unCheckedChildren="关"
              onChange={async (enabled) => {
                try {
                  const { code: resCode } = await changeTagStatus({
                    id: record.id,
                    status: enabled ? '1' : '0',
                  });
                  if (resCode === 0) {
                    refresh(params);
                  }
                } catch (e) {
                  console.error(e);
                }
              }}
            />
          );
        },
      },
      {
        title: '关联组织',
        dataIndex: 'orgNames',
        width: 150,
        render: text => (
          <Ellipsis length={20} tooltip fullWidthRecognition>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '关联用户',
        dataIndex: 'employeeNames',
        width: 150,
        render: text => (
          <Ellipsis length={20} tooltip fullWidthRecognition>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '标签描述',
        dataIndex: 'labelDesc',
        width: 200,
        render: text => (
          <Ellipsis length={20} tooltip fullWidthRecognition>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '操作',
        key: 'action',
        width: 160,
        fixed: 'right',
        render: record => (
          <div>
            <Button
              style={{ padding: 0 }}
              type="link"
              onClick={() => dispatch({ type: ACTIONS.PREVIEW, payload: record })}
            >
              详情
            </Button>
            <Divider type="vertical" />
            <Button
              style={{ padding: 0 }}
              type="link"
              onClick={() => dispatch({ type: ACTIONS.EDIT, payload: record })}
            >
              编辑
            </Button>
            <Divider type="vertical" />
            <Popconfirm
              title="确定要删除该岗位标签吗？"
              onConfirm={() => {
                removeTag([record.id]).then((res) => {
                  if (res.code === 0) {
                    refresh(params);
                    resetSelection();
                  }
                });
              }}
            >
              <Button style={{ padding: 0 }} type="link">
                删除
              </Button>
            </Popconfirm>
          </div>
        ),
      },
    ],
    [refresh, params, resetSelection],
  );

  return (
    <div className={styles.root}>
      <TopQueryForm
        submit={(...args) => {
          resetSelection();
          submit(...args);
        }}
        reset={reset}
        form={form}
      />
      <div className={styles.bottomWrapper}>
        <div className={styles.rightTable}>
          <div className={styles.rightTableTop}>
            <div className={styles.left}>
              <div className={styles.title}>岗位标签列表</div>
            </div>
            <div className={styles.right}>
              {selectedRowKeys.length !== 0 && (
                <Alert
                  type="info"
                  message={(
                    <>
                      已选中
                      {' '}
                      <strong>{selectedRowKeys.length}</strong>
                      {' '}
                      条数据
                      <Button
                        type="link"
                        size="small"
                        onClick={() => {
                          resetSelection();
                        }}
                      >
                        清空
                      </Button>
                    </>
                  )}
                  style={{ display: 'inline-block', padding: '3px 6px' }}
                />
              )}
              <Button
                type="danger"
                disabled={selectedRowKeys.length === 0}
                onClick={() => {
                  Modal.confirm({
                    title: '确认删除',
                    content: '确定要删除所有选中的岗位标签吗？',
                    onOk() {
                      removeTag(selectedRowKeys).then((res) => {
                        if (res.code === 0) {
                          resetSelection();
                          refresh(params);
                        } else {
                          message.error(res.message);
                        }
                      });
                    },
                    onCancel() {},
                  });
                }}
              >
                批量删除
              </Button>
              <Button type="primary" onClick={() => dispatch({ type: ACTIONS.ADD })}>
                新增岗位标签
              </Button>
            </div>
          </div>
          <div className={styles.tableWrapper}>
            <Table
              {...tableProps}
              columns={columns}
              pagination={{
                ...tableProps.pagination,
                showQuickJumper: true,
                showSizeChanger: false,
                showTotal: (total, range) => `总共${total}条记录，共${Math.ceil(total / 10)}页`,
              }}
              rowKey="id"
              rowSelection={{
                selectedRowKeys,
                onChange: onSelectChange,
              }}
              scroll={{ x: 'max-content' }}
            />
          </div>
        </div>
      </div>
      {state.visible && (
        <ModifyDrawer
          tagId={state?.currentTag?.id}
          mode={state?.mode}
          reloadParent={() => {
            if (state?.mode === ACTIONS.EDIT) {
              refresh(params);
            } else {
              reset();
            }
          }}
          onClose={handleDrawerClose}
          visible={state.visible}
        />
      )}
    </div>
  );
};

export default PositionTagManage;
